package com.njwb.day15.zqzb.jdbc03;

import com.njwb.day15.zqzb.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class AddStudent {


    public static void add(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入姓名：");
        String name = scanner.next();
        System.out.println("请输入年龄：");
        int age = scanner.nextInt() ;
        System.out.println("请输入住址：");
        String address=scanner.next();
        //构建连接对象
        Connection connection= null ;
        //命令器
        PreparedStatement pstmt= null ;
        try {
            connection = DbUtil.getConnection();
            //3、准备sql
            String sql = "insert into tb_student(sname,age,address) values(?,?,?)";
            //4、创建命令器
            pstmt = connection.prepareStatement(sql);
            //5、设置参数
            pstmt.setString(1,name);
            pstmt.setInt(2,age);
            pstmt.setString(3,address);
            //6、执行sql语句 executeUpdate该方法主要用做更新操作,返回值表示受影响的行数
            int result = pstmt.executeUpdate();
            if(result>0) {
                System.out.println("数据添加成功！！！");
            }
        }  catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //6、关闭资源 （倒着关闭）
            DbUtil.closeConnection(null,pstmt,connection);
        }
    }
}
